<template>
  <ProjectInfo
    :projectId="`${route.query.projectId}`"
    :reportType="'EEFZ'"
    :sign="true"
    :sync="true"
    :sync-content="'从预采样单中获取设备信息'"
    @on-sync-header="syncSchemeData"
    :preview=true
    @preview-file="onPreviewHeader"
  />
  <div class="flex h-[calc(100vh-100px)] flex-col">
    <!-- 设备领用信息表格 -->
    <ContentWrap class="h-full flex flex-col">
      <!-- Header Container for Title and Buttons -->
<!--      <div class="header-container-equipment">-->
<!--        &lt;!&ndash; Title Centered &ndash;&gt;-->
<!--        <h2 class="centered-title-equipment">现场仪器设备出入登记及校准</h2>-->
<!--        &lt;!&ndash; Buttons Right Aligned &ndash;&gt;-->
<!--        <div class="header-button-container-equipment">-->
<!--          <el-button type="primary" @click="toReviewCalibration">预览领用表</el-button>-->
<!--          <el-button type="primary" @click="toReviewCheck">预览校验表</el-button>-->
<!--        </div>-->
<!--      </div>-->
      <!-- 校准环境条件 -->
      <div class="calibration-environment mb-4">
        <div class="env-conditions">
          <div class="env-item">
            <span class="env-label">气温℃：</span>
            <el-input
              v-model="calibrationEnv.temperature"
              class="env-input"
              placeholder="请输入气温"
              @blur="validateTemperature"
            />
          </div>
          <div class="env-item">
            <span class="env-label">湿度%：</span>
            <el-input
              v-model="calibrationEnv.humidity"
              class="env-input"
              placeholder="请输入湿度"
              @blur="validateHumidity"
            />
          </div>
          <div class="env-item">
            <span class="env-label">气压：</span>
            <el-input
              v-model="calibrationEnv.pressure"
              class="env-input"
              placeholder="请输入气压"
              @blur="validatePressure"
            />
            <span class="env-unit">kpa</span>
          </div>
        </div>
      </div>
      <el-table
        :data="tableData"
        :show-overflow-tooltip="true"
        :stripe="true"
        class="flex-1 equipment-table"
      >
        <el-table-column align="center" label="序号" type="index" width="60" />
        <el-table-column align="center" label="设备名称" prop="equipmentName" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.equipmentName" placeholder="请输入设备名称" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="型号" prop="model" width="110">
          <template #default="scope">
            <el-input v-model="scope.row.model" placeholder="请输入型号" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="编号" prop="serialNumber" width="110">
          <template #header>
            <div class="header-with-icon">
              编号
              <el-tooltip content="点击将第一行的编号复制到所有行" placement="top">
                <el-icon class="copy-icon" @click.stop="copyToAllRows('serialNumber')">
                  <Brush />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
          <template #default="scope">
            <el-input v-model="scope.row.serialNumber" placeholder="请输入编号" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="calibrationEquipment" width="140">
          <template #header>
            <div class="header-with-icon">
              校准设备
              <el-tooltip content="点击将第一行的校准设备复制到所有行" placement="top">
                <el-icon class="copy-icon" @click.stop="copyToAllRows('calibrationEquipment')">
                  <Brush />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
          <template #default="scope">
            <el-input
              v-model="scope.row.calibrationEquipment"
              placeholder="双击选择校准设备"
              readonly
              @dblclick="openCalibrationEquipmentDialog(scope.$index)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="standardValue" width="90">
          <template #header>
            <div class="header-with-icon">
              标准值
              <el-tooltip content="点击将第一行的标准值复制到所有行" placement="top">
                <el-icon class="copy-icon" @click.stop="copyToAllRows('standardValue')">
                  <Brush />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
          <template #default="scope">
            <el-input v-model="scope.row.standardValue" placeholder="标准值" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="borrowStartTime" width="200">
          <template #header>
            <div class="header-with-icon">
              借用开始时间
              <el-tooltip content="点击将第一行的借用开始时间复制到所有行" placement="top">
                <el-icon class="copy-icon" @click.stop="copyToAllRows('borrowStartTime')">
                  <Brush />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.borrowStartTime"
              :disabled-date="disabledDate"
              placeholder="选择开始时间"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="validateStartTime(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="borrowEndTime" width="200">
          <template #header>
            <div class="header-with-icon">
              借用结束时间
              <el-tooltip content="点击将第一行的借用结束时间复制到所有行" placement="top">
                <el-icon class="copy-icon" @click.stop="copyToAllRows('borrowEndTime')">
                  <Brush />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.borrowEndTime"
              :disabled-date="(date) => disabledEndDate(date, scope.row.borrowStartTime)"
              placeholder="选择结束时间"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="validateEndTime(scope.row)"
            />
          </template>
        </el-table-column>
        <!-- 测试值列组 -->
        <el-table-column align="center" label="测试值" width="100">
          <el-table-column align="center" label="1" prop="testValue1">
            <template #default="scope">
              <el-input v-model="scope.row.testValue1" placeholder="测试值1" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="2" prop="testValue2">
            <template #default="scope">
              <el-input v-model="scope.row.testValue2" placeholder="测试值2" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="3" prop="testValue3">
            <template #default="scope">
              <el-input v-model="scope.row.testValue3" placeholder="测试值3" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="平均值" prop="testValueAvg">
            <template #default="scope">
              <div class="test-value-avg-container">
                <el-input
                  v-model="scope.row.testValueAvg"
                  :class="{ 'error-input': scope.row.testValueWarning }"
                  :disabled="true"
                  class="avg-input"
                  placeholder="平均值"
                />
                <el-tooltip
                  v-if="scope.row.testValueWarning"
                  :content="scope.row.testValueWarningMessage"
                  effect="dark"
                  placement="top"
                >
                  <el-icon class="warning-icon">
                    <Warning />
                  </el-icon>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作">
          <template #default="scope">
            <div class="flex justify-center flex-wrap gap-2">
              <el-button link type="danger" @click="deleteRow(scope.$index)"> 删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="mt-4 flex justify-end"></div>
    </ContentWrap>
  </div>

  <!-- 设备选择对话框 -->
  <el-dialog
    v-model="facilityDialogVisible"
    append-to-body
    destroy-on-close
    title="选择设备"
    width="60%"
  >
    <div class="dialog-content">
      <Facility
        :default-status="1"
        :show-selection="true"
        @selection-change="handleFacilitySelectionChange"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="facilityDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleFacilityConfirm">确 定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 新增：校准设备选择对话框 -->
  <el-dialog
    v-model="calibrationEquipmentDialogVisible"
    append-to-body
    destroy-on-close
    title="选择校准设备"
    width="60%"
  >
    <div class="dialog-content">
      <!-- 嵌入 Facility 组件，并开启选择模式，监听选择变化事件 -->
      <Facility
        :default-status="1"
        :show-selection="true"
        @selection-change="handleCalibrationEquipmentSelectionChange"
        @handle-facility-confirm="handleCalibrationEquipmentConfirm"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCalibrationEquipmentCancel">取 消</el-button>
        <el-button type="primary" @click="handleCalibrationEquipmentConfirm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { useMessage } from '@/hooks/web/useMessage'
import { ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
// 引入设备组件
import Facility from '@/views/infra/facility/facility.vue'
// 导入Element Plus图标
import { Brush, Warning } from '@element-plus/icons-vue'
import { FacilityLogApi } from '@/api/infra/facilitylog'
// 引入设备状态管理
import { type EquipmentRow } from '@/store/modules/sample'
// 引入流量计组件
// 引入 Flowmeter 组件的数据类型
import ProjectInfo from '@/views/project/list/ProjectInfo.vue'

/** 项目 列表 */
defineOptions({ equipmentName: 'EquipmentCollection' })

const route = useRoute()
const router = useRouter()
const projectId = ref(route.query.projectId as string)

const message = useMessage()

// 使用设备状态存储
// 本地状态（不使用全局 equipmentStore）
const calibrationEnv = reactive({ temperature: '', humidity: '', pressure: '' })

// 表格数据 (设备领用)
const tableData = ref<EquipmentRow[]>([]) // 仍然保留本地状态，因为 saveEquipmentData 会覆盖 store 中的 equipmentList

// 设备选择对话框
const facilityDialogVisible = ref(false)
const selectedFacilities = ref([])
const loading = ref(true) // 列表的加载中
// 后端保存（防抖）
let saveTimer: any = null
const isSaving = ref(false)
const doSave = async () => {
  if (isSaving.value) return
  isSaving.value = true
  try {
    await FacilityLogApi.saveFacilityReceive({
      projectId: projectId.value,
      calibrationEnv,
      equipmentList: tableData.value
    })
  } catch (e) {
    console.warn('设施日志保存失败', e)
  } finally {
    isSaving.value = false
  }
}
const debouncedSave = () => {
  if (saveTimer) clearTimeout(saveTimer)
  saveTimer = setTimeout(() => {
    doSave()
  }, 500)
}
// 新增：流量计对话框
const flowmeterDialogVisible = ref(false)

// 新增：校准设备选择对话框
const calibrationEquipmentDialogVisible = ref(false)
const selectedCalibrationEquipment = ref([])
const currentCalibrationRowIndex = ref(-1) // 当前正在选择校准设备的行索引
const queryParams = reactive({
  pageNo: 1,
  pageSize: 300,
  projectId: route.query.projectId
})

const syncSchemeData = async () => {
  try {
    await ElMessageBox.confirm('已有数据将被覆盖，确认是否同步？', '确认同步', {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
  } catch (_) {
    return
  }
  loading.value = true
  try {
    const data = await FacilityLogApi.getFacilityLogPage(queryParams)
    console.log('【EquipmentCollection】同步数据返回:', data)

    // 将返回的数据转换为表格数据格式
    if (data && data.list && Array.isArray(data.list)) {
      const convertedData = data.list.map((item, index) => ({
        id: item.id || '',
        equipmentName: item.equipmentName || '',
        model: item.model || '',
        serialNumber: item.serialNumber || '',
        calibrationEquipment: '',
        standardValue: '',
        borrowStartTime: item.borrowStartTime
          ? new Date(item.borrowStartTime).toISOString().slice(0, 19).replace('T', ' ')
          : '',
        borrowEndTime: item.borrowEndTime
          ? new Date(item.borrowEndTime).toISOString().slice(0, 19).replace('T', ' ')
          : '',
        facilityId: item.equipmentId || item.id,
        testValue1: '',
        testValue2: '',
        testValue3: '',
        testValueAvg: ''
      }))

      // 更新表格数据
      tableData.value = convertedData

      // 更新本地状态
      tableData.value = convertedData
      debouncedSave()

      message.success(`成功同步 ${convertedData.length} 条设备记录`)
    } else {
      message.warning('未获取到设备数据')
      tableData.value = []
    }
  } catch (error) {
    console.error('【EquipmentCollection】同步数据失败:', error)
    message.error('同步数据失败')
  } finally {
    loading.value = false
  }
}

// 校准环境条件
const onPreviewHeader = () => {
  // 跳转到现场调查页面，并携带项目信息
  const { projectId, projectNo } = route.query
  router.push({
    path: '/previewFile',
    query: {
      projectId: projectId,
      projectNo: projectNo,
      operationType: 41
    }
  })
}
// 校准环境条件
const toReviewCalibration = () => {
  // 跳转到现场调查页面，并携带项目信息
  const { projectId, projectNo } = route.query
  router.push({
    path: '/previewFile',
    query: {
      projectId: projectId,
      projectNo: projectNo,
      operationType: 4
    }
  })
}
const toReviewCheck = () => {
  // 跳转到现场调查页面，并携带项目信息
  const { projectId, projectNo } = route.query
  router.push({
    path: '/previewFile',
    query: {
      projectId: projectId,
      projectNo: projectNo,
      operationType: 5
    }
  })
}

// 只允许选择今天及以后的日期
const disabledDate = (date: Date) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return date < today
}

// 结束时间的禁用日期逻辑：必须大于开始时间
const disabledEndDate = (date: Date, startTime: string) => {
  // 首先应用基本的禁用规则（今天之前的日期不可选）
  if (disabledDate(date)) {
    return true
  }

  // 如果有开始时间，则结束时间必须大于开始时间
  if (startTime) {
    const startDate = new Date(startTime)
    return date < startDate
  }

  return false
}

// 验证开始时间
const validateStartTime = (row) => {
  if (row.borrowStartTime && row.borrowEndTime) {
    const startTime = new Date(row.borrowStartTime).getTime()
    const endTime = new Date(row.borrowEndTime).getTime()

    if (startTime >= endTime) {
      message.warning('借用开始时间必须小于借用结束时间')
      row.borrowStartTime = ''
    }
  }
}

// 验证结束时间
const validateEndTime = (row) => {
  if (row.borrowStartTime && row.borrowEndTime) {
    const startTime = new Date(row.borrowStartTime).getTime()
    const endTime = new Date(row.borrowEndTime).getTime()

    if (endTime <= startTime) {
      message.warning('借用结束时间必须大于借用开始时间')
      row.borrowEndTime = ''
    }
  }
}

// 删除行 (原设备领用表格)
const deleteRow = (index) => {
  // 调用 store 的 action 来删除设备领用数据
  tableData.value.splice(index, 1)
  debouncedSave()
  debouncedSave()
}

// 将第一行的指定字段复制到所有行
const copyToAllRows = (field) => {
  if (tableData.value.length <= 1) {
    message.warning('至少需要两行数据才能执行复制操作')
    return
  }

  const firstRowValue = tableData.value[0][field]
  if (firstRowValue === undefined || firstRowValue === '') {
    message.warning('第一行的该字段值为空，无法复制')
    return
  }

  ElMessageBox.confirm(`确定要将第一行的${getFieldName(field)}复制到所有行吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 从第二行开始复制
      for (let i = 1; i < tableData.value.length; i++) {
        tableData.value[i][field] = firstRowValue
      }
      message.success(`已将第一行的${getFieldName(field)}复制到所有行`)

      debouncedSave()
      debouncedSave()
    })
    .catch(() => {
      // 用户取消操作
    })
}

// 获取字段的中文名称
const getFieldName = (field) => {
  const fieldMap = {
    serialNumber: '编号',
    calibrationEquipment: '校准设备',
    standardValue: '标准值',
    borrowStartTime: '借用开始时间',
    borrowEndTime: '借用结束时间'
  }
  return fieldMap[field] || field
}

// 处理设备多选变化
const handleFacilitySelectionChange = (selection) => {
  selectedFacilities.value = selection
}

// 设备选择确认
const handleFacilityConfirm = () => {
  console.log('【EquipmentCollection】设备选择确认，当前选中的设备:', selectedFacilities.value)

  if (selectedFacilities.value.length === 0) {
    message.warning('请选择设备')
    return
  }

  // 获取当前页面已存在的 facilityId 列表
  const existingFacilityIds = new Set(tableData.value.map((row) => row.facilityId || row.id))

  const newRows: EquipmentRow[] = []
  const duplicateFacilities: any[] = []

  // 过滤掉已经存在的设备
  selectedFacilities.value.forEach((facility: any) => {
    if (!existingFacilityIds.has(facility.id)) {
      newRows.push({
        id: '', // 新增记录时id设为空字符串
        equipmentName: facility.equipmentName,
        model: facility.model,
        serialNumber: facility.serialNumber,
        calibrationEquipment: '',
        standardValue: '',
        borrowStartTime: '',
        borrowEndTime: '',
        facilityId: facility.id, // 保存设备ID用于关联
        testValue1: '',
        testValue2: '',
        testValue3: '',
        testValueAvg: ''
      })
    } else {
      duplicateFacilities.push(facility.equipmentName)
    }
  })

  if (newRows.length > 0) {
    // 追加到本地表格并保存
    tableData.value = [...tableData.value, ...newRows]
    debouncedSave()
  } else {
    console.log('【EquipmentCollection】设备选择确认，没有新设备添加')
  }

  facilityDialogVisible.value = false

  // 可选：提示用户有哪些设备是重复选择的
  if (duplicateFacilities.length > 0) {
    message.warning(`以下设备已存在，无法重复添加: ${duplicateFacilities.join('、')}`)
  }
}

// 新增：打开校准设备选择对话框
const openCalibrationEquipmentDialog = (rowIndex: number) => {
  currentCalibrationRowIndex.value = rowIndex
  calibrationEquipmentDialogVisible.value = true
  selectedCalibrationEquipment.value = [] // 清空之前的选择
}

// 新增：处理校准设备多选变化
const handleCalibrationEquipmentSelectionChange = (selection: any[]) => {
  console.log('【EquipmentCollection】校准设备选择变化:', selection)
  selectedCalibrationEquipment.value = selection
}

// 新增：校准设备选择确认
const handleCalibrationEquipmentConfirm = () => {
  console.log(
    '【EquipmentCollection】校准设备选择确认，当前选中的设备:',
    selectedCalibrationEquipment.value
  )

  if (!selectedCalibrationEquipment.value || selectedCalibrationEquipment.value.length === 0) {
    message.warning('请选择校准设备')
    return
  }

  if (
    currentCalibrationRowIndex.value >= 0 &&
    currentCalibrationRowIndex.value < tableData.value.length
  ) {
    // 只取第一个选中的设备作为校准设备（虽然支持多选，但只使用第一个）
    const selectedEquipment = selectedCalibrationEquipment.value[0]
    // 拼接设备名称、型号和编号
    const equipmentName = selectedEquipment.equipmentName || selectedEquipment.name || ''
    const model = selectedEquipment.model || ''
    const serialNumber = selectedEquipment.serialNumber || ''
    const displayText = [equipmentName, model, serialNumber].filter(Boolean).join('/')
    tableData.value[currentCalibrationRowIndex.value].calibrationEquipment = displayText

    // 持久化到后端
    debouncedSave()

    message.success('校准设备选择成功')
  }

  calibrationEquipmentDialogVisible.value = false
  selectedCalibrationEquipment.value = []
  currentCalibrationRowIndex.value = -1
}

// 新增：校准设备选择取消
const handleCalibrationEquipmentCancel = () => {
  calibrationEquipmentDialogVisible.value = false
  selectedCalibrationEquipment.value = []
  currentCalibrationRowIndex.value = -1
}

// 监听测试值变化，计算平均值
// 这里的 watch 监听的是 tableData，而 tableData 现在是 store.equipmentList 的副本
// 如果希望在 store.equipmentList 变化时也触发计算，可能需要调整 watch 源
watch(
  tableData, // 监听本地 tableData 的变化
  (newValue) => {
    newValue.forEach((row) => {
      if (row.testValue1 && row.testValue2 && row.testValue3) {
        const val1 = parseFloat(row.testValue1) || 0
        const val2 = parseFloat(row.testValue2) || 0
        const val3 = parseFloat(row.testValue3) || 0

        // 计算平均值并保留两位小数
        const avg = (val1 + val2 + val3) / 3
        row.testValueAvg = avg.toFixed(2)

        // 检查平均值与标准值的差异
        validateTestValueWithStandard(row, avg)
      } else {
        row.testValueAvg = ''
      }
    })

    console.log('【EquipmentCollection】tableData 变化:', newValue)
    debouncedSave()
  },
  { deep: true }
)

// 监听标准值变化，检查与平均值的差异
watch(
  () => tableData.value.map((row) => row.standardValue), // 监听本地 tableData 的 standardValue 变化
  () => {
    console.log('【EquipmentCollection】tableData standardValue 变化')
    tableData.value.forEach((row) => {
      if (row.testValueAvg && row.standardValue) {
        validateTestValueWithStandard(row, parseFloat(row.testValueAvg))
      }
    })
    // 标准值变化不直接保存到 store，因为它是在 tableData 内部，watch tableData 会处理保存
    // 但为了确保一致性，我们可以在这里也触发一次 saveEquipmentData，或者依赖上面的 watch(tableData)
    // 依赖 watch(tableData) 可能更合适，因为它 deep watch 整个 tableData
  },
  { deep: true }
)

// 监听校准环境条件变化
// calibrationEnv 现在是 store 的 ref，直接 watch 这个 ref
watch(
  calibrationEnv,
  () => {
    debouncedSave()
  },
  { deep: true }
)

// 验证测试值平均值与标准值的差异
const validateTestValueWithStandard = (row, avgValue) => {
  if (!row.standardValue) return

  const standardValue = parseFloat(row.standardValue)
  if (isNaN(standardValue) || standardValue === 0) return

  // 计算差异百分比
  const difference = Math.abs(avgValue - standardValue)
  const percentDiff = (difference / standardValue) * 100

  // 如果差异超过5%，显示警告
  if (percentDiff > 5) {
    // 添加警告标记
    row.testValueWarning = true
    row.testValueWarningMessage = `测试值平均值与标准值相差${percentDiff.toFixed(2)}%，超过允许的5%`
  } else {
    // 清除警告标记
    row.testValueWarning = false
    row.testValueWarningMessage = ''
  }
}

// 校验气温
const validateTemperature = () => {
  const env = calibrationEnv
  if (!env.temperature) return
  const temp = parseFloat(env.temperature)
  if (isNaN(temp)) {
    message.warning('气温必须是数字')
    env.temperature = ''
    return
  }
  if (temp < -10 || temp > 45) {
    message.warning('气温值超出合理范围（-10°C到45°C）')
    env.temperature = ''
  }
}

// 校验湿度
const validateHumidity = () => {
  const env = calibrationEnv
  if (!env.humidity) return
  const humidity = parseFloat(env.humidity)
  if (isNaN(humidity)) {
    message.warning('湿度必须是数字')
    env.humidity = ''
    return
  }
  if (humidity < 0 || humidity > 100) {
    message.warning('湿度值必须在0-100%之间')
    env.humidity = ''
  }
}

// 校验气压
const validatePressure = () => {
  const env = calibrationEnv
  if (!env.pressure) return
  const pressure = parseFloat(env.pressure)
  if (isNaN(pressure)) {
    message.warning('气压必须是数字')
    env.pressure = ''
    return
  }
  if (pressure < 80 || pressure > 110) {
    message.warning('气压值超出合理范围（80-110 kPa）')
    env.pressure = ''
  }
}

// 获取数据库中设备领用信息并回显到页面
const facilityReceiveInfo = async () => {
  if (!projectId.value) return
  try {
    const response: any = await FacilityLogApi.facilityReceiveInfo(Number(projectId.value))
    console.log('【EquipmentCollection】facilityReceiveInfo 返回数据:', response)

    const respEnv = response?.calibrationEnv || { temperature: '', humidity: '', pressure: '' }
    calibrationEnv.temperature = respEnv.temperature || ''
    calibrationEnv.humidity = respEnv.humidity || ''
    calibrationEnv.pressure = respEnv.pressure || ''

    // 规范化设备列表为表格行结构
    const equipmentList: EquipmentRow[] = Array.isArray(response?.equipmentList)
      ? response.equipmentList.map((item: any) => ({
          id: item.id ?? '',
          equipmentName: item.equipmentName ?? '',
          model: item.model ?? '',
          serialNumber: item.serialNumber ?? '',
          calibrationEquipment: item.calibrationEquipment ?? '',
          standardValue: item.standardValue ?? '',
          borrowStartTime: item.borrowStartTime ?? '',
          borrowEndTime: item.borrowEndTime ?? '',
          facilityId: item.facilityId ?? item.equipmentId ?? '',
          testValue1: item.testValue1 ?? '',
          testValue2: item.testValue2 ?? '',
          testValue3: item.testValue3 ?? '',
          testValueAvg: item.testValueAvg ?? ''
        }))
      : []

    tableData.value = equipmentList
  } catch (e) {
    console.error('【EquipmentCollection】facilityReceiveInfo 加载失败', e)
  }
}

/** 初始化 **/
onMounted(() => {
  console.log('【EquipmentCollection】组件挂载')
  facilityReceiveInfo()
})
</script>

<style lang="scss" scoped>
.flex {
  display: flex;
}

.h-[calc\(100vh-100px\)] {
  height: calc(100vh - 100px);
}

.flex-1 {
  flex: 1;
}

.flex-col {
  flex-direction: column;
}

.p-4 {
  padding: 1rem;
}

.mb-4 {
  margin-bottom: 1rem;
}

.justify-between {
  justify-content: space-between;
}

.justify-end {
  justify-content: flex-end;
}

.justify-center {
  justify-content: center;
}

.items-center {
  align-items: center;
}

.text-lg {
  font-size: 1.125rem;
}

.font-bold {
  font-weight: 700;
}

/* Header Container for Title and Buttons */
.header-container-equipment {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e5e6eb;
}

/* Centered Title */
.centered-title-equipment {
  text-align: center; // Center the text
  flex-grow: 1; // Allow title to take available space to help centering
  margin: 0; // Remove default margin
  font-size: 24px; // Match Consumable title size
  font-weight: bold;
}

/* Button Container Right Aligned */
.header-button-container-equipment {
  text-align: right; // Align buttons to the right
  // No flex-grow here, let it take only needed space
}

/* 表头带图标样式 */
.header-with-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px; /* 调整文字和图标之间的间距 */
  position: relative;
}

.copy-icon {
  cursor: pointer;
  width: 16px;
  height: 16px;
  transition: transform 0.2s;

  &:hover {
    transform: scale(1.2);
  }

  svg {
    width: 16px;
    height: 16px;
  }
}

.equipment-table {
  :deep(.el-table__header) {
    th {
      padding: 8px 0;
    }
  }
}

:deep(.el-table__header) {
  font-weight: 600;

  th {
    background-color: var(--el-table-header-bg-color);
    padding: 12px 0;
    height: 50px;
    font-size: 14px;
  }
}

:deep(.el-table__body) {
  td {
    padding: 12px 0;
    height: 56px;
  }
}

:deep(.el-input__wrapper) {
  padding: 0 8px;
}

:deep(.el-input__inner) {
  height: 32px;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

.dialog-content {
  padding: 0;
  height: 70vh;
  overflow: auto;
}

.dialog-footer {
  padding: 20px;
  text-align: right;
}

:deep(.el-dialog__body) {
  padding: 0;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

:deep(.el-dialog__footer) {
  margin: 0;
  padding: 0;
  border-top: 1px solid var(--el-border-color-lighter);
}

.flex-wrap {
  flex-wrap: wrap;
}

.gap-2 {
  gap: 0.5rem;
}

.mt-4 {
  margin-top: 1rem;
}

/* 调整日期选择器样式 */
:deep(.el-date-editor) {
  width: 100%;
  min-width: 160px;
}

/* 调整弹框宽度 */
:global(.wider-message-box) {
  width: 610px !important;
  max-width: 90% !important;
}

/* 测试值平均值样式 */

.test-value-avg-container {
  display: flex;
  align-items: center;
  width: 100%; /* Ensure container takes full width */
}

.avg-input {
  flex-grow: 1; /* Allow input to fill space */
  margin-right: 5px; /* Space between input and icon */
}

.warning-icon {
  color: #e6a23c;
  font-size: 16px;
  // position: absolute; // Remove absolute positioning
  // right: 0; // Remove right positioning
  z-index: 2;
}

:deep(.error-input .el-input__wrapper) {
  box-shadow: 0 0 0 1px #e6a23c inset !important;
  background-color: #fdf6ec !important;
}

/* 保存时的警告提示 */
.test-value-warning {
  color: #e6a23c;
  margin-top: 5px;
  font-size: 12px;
}

/* 校准环境条件样式 */
.calibration-environment {
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px; // Added border-radius for consistency
  margin-bottom: 20px; // Added margin-bottom for consistency
}

.env-conditions {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.env-item {
  display: flex;
  align-items: center;
}

.env-label {
  flex-shrink: 0; // Prevent label from shrinking
}

.env-input {
  width: 100px;
  // Adjust input wrapper/inner styles for consistency with table inputs if desired
  :deep(.el-input__wrapper) {
    padding: 0 8px;
    box-shadow: none !important;
    background-color: transparent !important;
    border-bottom: 1px solid var(--el-border-color); // Add a subtle bottom border
    border-radius: 0;
  }

  :deep(.el-input__inner) {
    height: auto;
    line-height: inherit;
  }
}

.env-unit {
  margin-left: 5px;
  color: #606266;
}
</style>
